package com.yangyao.microserviceoauth2.authority.service.impl;

import com.yangyao.microserviceoauth2.authority.entity.Permission;
import com.yangyao.microserviceoauth2.authority.entity.User;
import com.yangyao.microserviceoauth2.authority.service.PermissionService;
import com.yangyao.microserviceoauth2.authority.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = this.userService.findUserByUserName(userName);
        if (user == null) {
            throw new UsernameNotFoundException("userName" + userName + "is not exists");
        }
        List<Permission> permissionList = this.permissionService.getPermissionsByUserId(user.getId());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        permissionList.forEach(permission -> {
            grantedAuthorities.add(new SimpleGrantedAuthority(permission.getEnname()));
        });
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), grantedAuthorities);

    }
}
